package com.xumx.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by Xumx on 2022/5/18 8:23
 */
@Api("用户登录管理")
@Controller
public class IndexController {

    @ApiOperation("访问首页面")
    @RequestMapping({"/","/index"})
    public String index(Model model){
        model.addAttribute("msg","hello,Shrio");
        return "index";
    }

    @ApiOperation("去添加页面")
    @RequestMapping("/user/add")
    public String toAdd(){
        return "user/add";
    }

    @RequestMapping("/user/update")
    public String toUpdate(){
        return "user/update";
    }

    @RequestMapping("/toLogin")
    public String login(){
        return "login";
    }

    @ApiOperation("登录请求")
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String toIndex(String username,String password,Model model){
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        try {
            subject.login(token);  //执行登录的方法，如果没有异常就说名ok
            return "index";
        } catch (UnknownAccountException e) {  //用户不存在
            model.addAttribute("msg","用户名错误");
            return "login";
        }catch (IncorrectCredentialsException e) {  //密码错误
            model.addAttribute("msg","密码错误");
            return "login";

        }
    }

    @RequestMapping("/noauth")
    @ResponseBody
    public String noauth(){
        return "未经授权，无法访问";
    }

}
